﻿using AutoMapper;
using MediatR;
using RBAC.Domain;
using RBAC.Domain.Dto.Output;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.User;
using System.Linq;

namespace RBAC.Read.Api.Application.Handler.User
{
    public class GetUserListHandler : IRequestHandler<GetUserListCommand, APIPaging<GetUserListDto>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<UserRoleModel> userroleRepository;
        private readonly ILogger<GetUserListHandler> logger;
        private readonly IMapper mapper;
        
        public GetUserListHandler(IBaseRepository<UserModel> userRepository, 
            IBaseRepository<RoleModel> roleRepository, 
            IBaseRepository<UserRoleModel> userroleRepository, 
            IMapper mapper, 
            ILogger<GetUserListHandler> logger)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.userroleRepository = userroleRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<GetUserListDto>> Handle(GetUserListCommand request, CancellationToken cancellationToken)
        {
            APIPaging<GetUserListDto> res = new APIPaging<GetUserListDto>();
            var users = userRepository.GetALL().Where(x => x.IsDeleted == false);
            var userroles = userroleRepository.GetALL().Where(x => x.IsDeleted == false);
            var roles = roleRepository.GetALL().Where(x => x.IsDeleted == false);
            
            if(request.UserName != null)
            {
                users = users.Where(x => x.UserName.Contains(request.UserName));
            }
            
            // 先获取用户与角色的关联数据
            var userRoleData = from a in users
                       join b in userroles on a.Id equals b.UserId
                       join c in roles on b.RoleId equals c.Id
                       select new 
                       {
                           Id = a.Id,
                           UserName = a.UserName,
                           Password = a.Password,
                           RoleName = c.RoleName,
                           RoleId=c.Id,
                           IsEnable = a.IsEnable
                       };
            
            // 按用户分组，将每个用户拥有的角色名称存储到集合中
            var groupedData = userRoleData
                .GroupBy(x => new { x.Id, x.UserName, x.Password, x.IsEnable })
                .Select(g => new GetUserListDto
                {
                    Id = g.Key.Id,
                    UserName = g.Key.UserName,
                    Password = g.Key.Password,
                    RoleName = g.Select(r => r.RoleName).ToList(),
                    RoleId=g.Select(r => r.RoleId).ToList(),
                    IsEnable = g.Key.IsEnable
                }).ToList();
                
            // 分页处理
            var pagedData = groupedData
                .Skip((request.Pageindex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToList();
                
            res.Code = APIEnums.Success;
            res.PageDatas = pagedData;
            res.TotalCount = groupedData.Count;
            res.Msg = "获取用户列表成功";
            logger.LogInformation("获取用户列表成功");
            return Task.FromResult(res);
        }
    }
}
